<template>
  <div class="rabbitmq-monitor">
    <div class="monitor-header">
      <h3>RabbitMQ监控面板</h3>
      <div class="monitor-controls">
        <el-switch
          v-model="autoRefresh"
          active-text="自动刷新"
          @change="toggleAutoRefresh"
        />
        <el-button size="small" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 连接状态 -->
    <div class="status-section">
      <div class="status-indicator" :class="getConnectionStatusClass()">
        <el-icon><Connection /></el-icon>
        <span>{{ getConnectionStatusText() }}</span>
      </div>
      
      <div class="queue-status" v-if="queueStatus.enabled">
        <el-tag :type="queueStatus.connected ? 'success' : 'danger'" size="small">
          队列{{ queueStatus.connected ? '已连接' : '未连接' }}
        </el-tag>
      </div>
    </div>

    <!-- 实时统计 -->
    <div class="stats-grid">
      <!-- 路由统计 -->
      <div class="stat-card">
        <div class="stat-header">
          <el-icon><Share /></el-icon>
          <span>消息路由</span>
        </div>
        <div class="stat-content">
          <div class="stat-item">
            <span class="stat-label">成功:</span>
            <span class="stat-value success">{{ routingStats.DIRECT_ROUTING_success || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">失败:</span>
            <span class="stat-value error">{{ routingStats.DIRECT_ROUTING_failure || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">成功率:</span>
            <span class="stat-value">{{ getSuccessRate() }}%</span>
          </div>
        </div>
      </div>

      <!-- 重试统计 -->
      <div class="stat-card">
        <div class="stat-header">
          <el-icon><RefreshRight /></el-icon>
          <span>消息重试</span>
        </div>
        <div class="stat-content">
          <div class="stat-item">
            <span class="stat-label">重试次数:</span>
            <span class="stat-value warning">{{ retryStats.retry_count || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">死信消息:</span>
            <span class="stat-value error">{{ retryStats.dead_letter_count || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- 队列统计 -->
      <div class="stat-card" v-if="queueStatus.enabled">
        <div class="stat-header">
          <el-icon><List /></el-icon>
          <span>队列状态</span>
        </div>
        <div class="stat-content">
          <div class="stat-item">
            <span class="stat-label">路由成功:</span>
            <span class="stat-value success">{{ queueStatus.stats.routingSuccess }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">路由失败:</span>
            <span class="stat-value error">{{ queueStatus.stats.routingFailure }}</span>
          </div>
        </div>
      </div>

      <!-- 在线状态 -->
      <div class="stat-card">
        <div class="stat-header">
          <el-icon><User /></el-icon>
          <span>在线状态</span>
        </div>
        <div class="stat-content">
          <div class="stat-item">
            <span class="stat-label">在线用户:</span>
            <span class="stat-value info">{{ onlineUsers }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">活跃团队:</span>
            <span class="stat-value info">{{ activeTeams }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能图表 -->
    <div class="chart-section" v-if="showCharts">
      <div class="chart-container">
        <h4>消息处理趋势</h4>
        <div class="chart-placeholder">
          <!-- 这里可以集成图表库如ECharts -->
          <div class="trend-line">
            <div 
              v-for="(point, index) in performanceHistory" 
              :key="index"
              class="trend-point"
              :style="{ height: `${point.value}%` }"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 最近错误日志 -->
    <div class="error-log-section" v-if="showErrorLog && errorLog.length > 0">
      <h4>最近错误</h4>
      <div class="error-log">
        <div 
          v-for="(error, index) in errorLog.slice(0, 5)" 
          :key="index"
          class="error-item"
        >
          <div class="error-time">{{ formatTime(error.timestamp) }}</div>
          <div class="error-message">{{ error.message }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { 
  Refresh, 
  Connection, 
  Share, 
  RefreshRight, 
  List, 
  User 
} from '@element-plus/icons-vue'
import { useTeamChatStore } from '@/stores/teamChat'

// Props
interface Props {
  showCharts?: boolean
  showErrorLog?: boolean
  refreshInterval?: number
}

const props = withDefaults(defineProps<Props>(), {
  showCharts: true,
  showErrorLog: true,
  refreshInterval: 5000
})

// Store
const teamChatStore = useTeamChatStore()

// 响应式数据
const autoRefresh = ref(true)
const refreshTimer = ref<NodeJS.Timeout | null>(null)
const routingStats = ref<Record<string, number>>({})
const retryStats = ref<Record<string, number>>({})
const performanceHistory = ref<Array<{ timestamp: number, value: number }>>([])
const errorLog = ref<Array<{ timestamp: number, message: string }>>([])

// 计算属性
const queueStatus = computed(() => teamChatStore.queueStatus)
const onlineUsers = computed(() => Object.keys(teamChatStore.teamSocketManager?.userClientMap || {}).length)
const activeTeams = computed(() => Object.keys(teamChatStore.teamMessages || {}).length)

// 方法
const getConnectionStatusClass = () => {
  if (!queueStatus.value.enabled) return 'status-disabled'
  return queueStatus.value.connected ? 'status-connected' : 'status-disconnected'
}

const getConnectionStatusText = () => {
  if (!queueStatus.value.enabled) return 'RabbitMQ未启用'
  return queueStatus.value.connected ? 'RabbitMQ已连接' : 'RabbitMQ连接断开'
}

const getSuccessRate = () => {
  const success = routingStats.value.DIRECT_ROUTING_success || 0
  const failure = routingStats.value.DIRECT_ROUTING_failure || 0
  const total = success + failure
  
  if (total === 0) return 100
  return Math.round((success / total) * 100)
}

const refreshData = async () => {
  try {
    // 这里应该调用API获取最新统计数据
    // 由于我们没有直接的API，这里模拟数据更新
    
    // 更新性能历史
    const currentTime = Date.now()
    const currentValue = Math.random() * 100
    
    performanceHistory.value.push({
      timestamp: currentTime,
      value: currentValue
    })
    
    // 保持最近20个数据点
    if (performanceHistory.value.length > 20) {
      performanceHistory.value.shift()
    }
    
    // 模拟错误日志更新
    if (Math.random() < 0.1) { // 10%概率添加错误日志
      errorLog.value.unshift({
        timestamp: currentTime,
        message: `模拟错误: 消息处理超时 (${Math.floor(Math.random() * 1000)}ms)`
      })
      
      // 保持最近10条错误日志
      if (errorLog.value.length > 10) {
        errorLog.value.pop()
      }
    }
    
  } catch (error) {
    console.error('刷新监控数据失败:', error)
  }
}

const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

const startAutoRefresh = () => {
  if (refreshTimer.value) return
  
  refreshTimer.value = setInterval(() => {
    refreshData()
  }, props.refreshInterval)
}

const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = null
  }
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString()
}

// 生命周期
onMounted(() => {
  refreshData()
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped lang="scss">
.rabbitmq-monitor {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    margin: 0;
    color: #303133;
  }
}

.monitor-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  
  &.status-connected {
    color: #67c23a;
  }
  
  &.status-disconnected {
    color: #f56c6c;
  }
  
  &.status-disabled {
    color: #909399;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  
  .stat-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-weight: 500;
    color: #303133;
  }
  
  .stat-content {
    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .stat-label {
        font-size: 14px;
        color: #606266;
      }
      
      .stat-value {
        font-weight: 600;
        
        &.success {
          color: #67c23a;
        }
        
        &.warning {
          color: #e6a23c;
        }
        
        &.error {
          color: #f56c6c;
        }
        
        &.info {
          color: #409eff;
        }
      }
    }
  }
}

.chart-section {
  margin-bottom: 20px;
  
  h4 {
    margin: 0 0 12px 0;
    color: #303133;
  }
}

.chart-container {
  .chart-placeholder {
    height: 120px;
    background: #f8f9fa;
    border-radius: 6px;
    padding: 16px;
    display: flex;
    align-items: end;
    justify-content: center;
  }
  
  .trend-line {
    display: flex;
    align-items: end;
    gap: 2px;
    height: 80px;
  }
  
  .trend-point {
    width: 4px;
    background: #409eff;
    border-radius: 2px;
    min-height: 2px;
    transition: height 0.3s ease;
  }
}

.error-log-section {
  h4 {
    margin: 0 0 12px 0;
    color: #303133;
  }
}

.error-log {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 6px;
  padding: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.error-item {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .error-time {
    font-size: 12px;
    color: #909399;
    white-space: nowrap;
  }
  
  .error-message {
    font-size: 14px;
    color: #f56c6c;
    flex: 1;
  }
}
</style>
